<template>
	<el-dialog :close-on-click-modal="false" title="上传头像" :visible.sync="show" width="45%" v-loading="loading">
		<el-form ref="form" :model="request.data" :inline="true" label-width="80px">
			<el-row>
				<el-col :span="12">
					<el-form-item label="头像">
						<el-upload action="#" :show-file-list="false" :auto-upload="false" :on-change="changeImg">
							<img v-if="request.data.head" :src="request.data.head" style="width: 100px;height: 100px;" />
							<i v-else class="el-icon-plus avatar-uploader-icon"></i>
						</el-upload>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button type="primary" @click="submitForm('form')">上传</el-button>
			<el-button @click="show = false">取 消</el-button>
		</div>
	</el-dialog>
</template>

<script>
import utils from 'util/utils.js';
import api from 'api/main.js';

export default {
	name: 'uploadHead',
	data() {
		return {
			isDisabled: false,
			loading: false,
			show: this.isDisplay,
			request: utils.newRequest()
		};
	},
	methods: {
		//提交表单
		submitForm(formName) {
			utils.checkForm(this.$refs[formName], () => {
				this.loading = true;
				api.uploadHead(
					this.request,
					response => {
						utils.msg.success(response.msg);
						this.loading = false;
						this.show = false;
						this.$parent.list();
					},
					response => {
						utils.msg.warning(response.msg);
						this.loading = false;
					}
				);
			});
		},
		getBase64(file) {
			return new Promise(function(resolve, reject) {
				let reader = new FileReader();
				let imgResult = '';
				reader.readAsDataURL(file);
				reader.onload = function() {
					imgResult = reader.result;
				};
				reader.onerror = function(error) {
					reject(error);
				};
				reader.onloadend = function() {
					resolve(imgResult);
				};
			});
		},
		//选择图片后
		changeImg(file, fileList) {
			this.getBase64(file.raw).then(res => {
				this.request.data.head = res;
			});
		},
		init() {
			this.request = utils.newRequest();
			api.toUploadHead(null, response => {
				this.request.data = response.data;
			});
		}
	},
	props: {
		isDisplay: {
			type: Boolean,
			default() {
				return false;
			}
		},
		parameter: {
			type: Array | Object,
			default() {
				return {};
			}
		}
	},
	watch: {
		isDisplay(val) {
			this.show = val;
			if (val) {
				this.init();
			}
		},
		show(val) {
			this.$emit('update:isDisplay', val);
		},
		parameter(val) {
			this.parameter = val;
		}
	}
};
</script>

<style lang="scss"></style>
